<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'><Input v-model.trim="searchData.name" placeholder="角色名称" clearable @on-enter="onSearchGetList()"></Input></div>    
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg' @click='editInfo(1,{})'><img src="../../assets/images/peach-svg/add.svg"></div>
      </div>
     </section>
    
      <template>
        <el-dialog :visible.sync="treeshow" class="treetree" :modal="true" title="权限修改">
          <el-tree
          :data="menuList"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree">
        </el-tree>

        <div class="buttons">
          <el-button @click="getCheckedNodes">取消</el-button>
          <el-button @click="getCheckedKeys">确定</el-button>
          <el-button @click="resetChecked">清空</el-button>
        </div>
      </el-dialog>
    </template>
   
    <!-- <myTable :tableColumns="tableColumns" :totalCnt="totalCnt" :tableData="list" :isShowPage="true" :isLoadData="true" @submit="onChangePageSize" :current="searchData.searchPage"></myTable> -->
    <LibVxeTable class="staticData" 
    :stripe="stripe" 
    :tableColumns="tableColumns"
     border="none" :tableData="list" 
     :slotHeader="slotHeader" 
     :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"
     @onPageChange="onChangePageSize" 
     resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,      
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        page_index:1,
        page_size:30,
        name:""
      },
      rows:[],
      treeshow:false,
      menuList:[],
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      channelList:[],
      cityList:[],
      cityInfo:[-1],
      partnerList:[],
      ChannelList:[],
      QdsPartnerList:[],
      QdsPartnerObj:{},
      BusinessList:[],
      BusinessObj:{},
      cityObj:{},
      brandObj:{},
      brandObjCh:{},
      tableColumns:[
        {
          title: "角色名称",
          field: "name",
          align: 'center',
        },
        {
          title: "别名",
          field: "alias",
          align: 'center',
        },
        {
          title: "操作",
          field: "action",
          // fixed:"right",          
          width: 150,
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];

                hButton.push(h(
                    "div",
                    {
                      class:"two",
                      on: {
                        click: () => {
                          this.editInfo(2,row);
                        }
                      }
                    },
                  ));
              
                hButton.push(
                  h(
                    "div",
                    {
                      class:"three",
                      on: {
                        click: () => {
                          this.sureDel(row,-1);
                        }
                      }
                    },
                  )
                )
                hButton.push(h(
                    "div",
                    {
                      class:"quanxian",
                      props:{
                        
                      },
                      on: {
                        click: () => {
                          this.trees(row);
                        }
                      }
                    },
                  ));
              
              return hButton;
            });
            }
          }
        }
      ],
      format: {  
        name:{
          labelName: "角色名称",
          labelType: "text",      
          placeholder:"请输入角色名称"
        },
        alias:{
          labelName: "别名",
          labelType: "text",      
          placeholder:"请输入别名"
        }

      },
      ruleValidate: {
        name: [{ required: true,message: "角色名称不能为空", trigger: "blur" }],
        alias:[{ required: true,message: "别名不能为空", trigger: "blur" }],
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      this.initDate();
      this.initSearchData();
    },
    async initSearchData(){
      let res = await Request.post("sys/menu","queryMenuDetail_list")
      this.menuList=[]
      if(res.code==0){
        res.data.ResourceList.forEach(item => {
          let info = this.loopResourceData(item);
          this.menuList.push(info)
        });
        console.log(this.menuList,"this.menuList")
      }
    },
    loopResourceData(item){
        let info = {id:item.ID,label:item.Title,Path:item.Name,children:[],ParentMod:item.Perms.length==0&&item.Children.length>0,Icon:item.Icon}
        // this.resourceMap.set(info.Path,info.Name);
        item.Children.forEach(childItem => {
          let childInfo = this.loopResourceData(childItem);
          if(!childInfo.ParentMod||childInfo.children.length>0){
              info.children.push(this.loopResourceData(childItem));
          }
        });
        return info;
    },
      //关闭弹窗
      getCheckedNodes() {
        this.treeshow=false
      },
      //添加权限方法
      async getCheckedKeys() {
        this.treeshow=false
        let keylist=this.$refs.tree.getCheckedKeys()//获取取到的id值
        console.log(keylist=="","keylist")
        let kkeys=[]//去除id为0的新数组
        let keystring=""
        if(keylist!=""){
          keylist.forEach(item => {
          (item!=0 && kkeys.push(item))//判断为0删除并加进新数组
          });
          //转成|隔开的字符串
          keystring=kkeys.join("|")
        }else{
          keystring="empty"
        }
        let res = await this.RequestPost("edit_item", 
          {id:this.rows.id,
          name:this.rows.name,
          alias:this.rows.alias,
          menu_ids:keystring
          });
          if(res.code==0){
            utils.showTip("权限修改成功！");
          }
      },
      resetChecked() {
        this.$refs.tree.setCheckedKeys([]);
      },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    //点击权限按钮弹窗
    async trees(row){
      this.rows=row//全局row信息
      this.treeshow=true
      let res = await Request.post("sys/menu","queryMenuDetail_list",{"role_id":row.id})
      let menucheckList=[]//二级菜单数组
      let menucheckListids=[]//二级菜单ID数组
      if(res.code==0){
        if(res.data.ResourceList != null && res.data != null){
          res.data.ResourceList.forEach(item => {
            item.Children.forEach(item2=>{
              menucheckList.push(item2)
            })
          });
        } 
      }
      menucheckList.forEach(item=>{
        menucheckListids.push(item.ID)
      })
      this.$refs.tree.setCheckedKeys(menucheckListids);//把已勾选的权限id显示
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      console.log(res);
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) 
        this.list = res.data.list;
        this.totalCnt = res.data.total
        // this.list.push({"totalName":"合计","Cnt":res.data.TotalUserCnt});
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    //添加 编辑用户
    async editInfo(type,row) {
        console.log(type);
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加用户";
        info = {
          name:"",
          alias:""
        };
      }else{
        if (row.Status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑用户";
        info = {
          id:row.id,
          name:row.name,
          alias:row.alias
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,labelWidth:150,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },    
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';         
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '修改成功！';          
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.id};
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }
      utils.hideLoading();
    },   
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.shadowModel(
            {
            "title":"删除提示",                  
            "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
            "modalContent":"确认删除 "+item.name+" ?",
            "callBackArgs":{"id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val){
      var b = val[0]
      var s = val[1]
      this.searchData.searchBeginDay = parseInt(b.replace(/-/g,""));
      this.searchData.searchEndDay = parseInt(s.replace(/-/g,""));
      this.onSearchGetList();
    },
    changeTime(val){
      if(val[0]!=""){
        this.searchTime = val;
      }else{
        this.searchTime = ['00:00','23:59'];
      }
      this.searchData.searchBeginDay = this.searchTime[0].split(":")[0]
      this.searchData.searchEndDay = this.searchTime[1].split(":")[0]
    },
    initDate(){
      let lastDay = utils.dateFormat(utils.getServerSysTime()-86400,"yyyy-MM-dd")
      let nowDay = utils.dateFormat(utils.getServerSysTime(),"yyyy-MM-dd")
      var mycars=new Array()
      mycars[0]=lastDay
      mycars[1]=nowDay
      this.searchDate = mycars;
      this.changeDate(mycars);
    },
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    filterPartner(item){
      // console.log("item ",item)
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1 ) return true
        return item.BusinessId==this.searchData.searchBusinessId;
    },
  },
};
</script>  